package com.pinyoumei.app.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.adapter.UserManageAdapter;
import com.pinyoumei.app.bean.UserManageBean;
import com.pinyoumei.app.fragment.SimpleCardFragment;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.view.OnTabSelectListener;
import com.pinyoumei.app.view.SlidingTabLayoutIcon;
import com.pinyoumei.app.view.dialog.CallDialog;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2021-08-12.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-12        Administrator             新增Person类
 * 2021-08-12        Administrator             增加sex属性
 * 客户管理
 */
public class UserManageActivity extends BaseActivity implements View.OnClickListener {


    private SlidingTabLayoutIcon tl_5;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<String> tabList = new ArrayList<>();
    private ViewPager vp;
    private int page = 1;
    private int recommand_level = 0;
    private String user_level_id = "";
    private String recommand_user_phone = "";
    private CircleImageView iv_recommand_user_head_img;
    private TextView tv_recommand_user_real_name;
    private List<UserManageBean.ResultBean.UserLevelListBean> user_level_list;
    private Button bt_1;
    private Button bt_2;
    private Button bt_3;
    private UserManageAdapter userManageAdapter;
    private EditText et_input;
    private RecyclerView rv1;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_manage);

        InitWidget();

        InitData("");

    }

    private void InitWidget() {

        et_input = findViewById(R.id.et_input);
        ImageView ivClose = findViewById(R.id.iv_close);
        ivClose.setOnClickListener(this);

        LinearLayout ll_phone = findViewById(R.id.ll_phone);
        ll_phone.setOnClickListener(this);
        RelativeLayout rl_search = findViewById(R.id.rl_search);
        rl_search.setOnClickListener(this);
        tl_5 = findViewById(R.id.tl_5);


        tl_5.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                for (int i = 0; i < tl_5.getTabCount(); i++) {
                    if (position == i) {
                        //选中的文字
                        tl_5.getTitleView(position).setTextSize(16f);
                        tl_5.getTitleView(0).setTypeface(Typeface.DEFAULT_BOLD);
                    } else {
                        //未选中的文字，并且设置未选中时的不加粗
                        tl_5.getTitleView(i).setTextSize(12f);
                        tl_5.getTitleView(0).setTypeface(Typeface.DEFAULT);

                    }
                }

                if (user_level_list!=null && user_level_list.size()>0){
                    user_level_id =user_level_list.get(position).getId();
                    String input = et_input.getText().toString().trim();
                    SetData(input);
                }

            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        vp = findViewById(R.id.vp);


        iv_recommand_user_head_img = findViewById(R.id.iv_recommand_user_head_img);
        tv_recommand_user_real_name = findViewById(R.id.tv_recommand_user_real_name);
        bt_1 = findViewById(R.id.bt_1);
        bt_1.setOnClickListener(this);
        bt_2 = findViewById(R.id.bt_2);
        bt_2.setOnClickListener(this);
        bt_3 = findViewById(R.id.bt_3);
        bt_3.setOnClickListener(this);


        rv1 = findViewById(R.id.rv_1);
        rv1.setLayoutManager(new GridLayoutManager(this, 1, GridLayoutManager.VERTICAL, false));
        userManageAdapter = new UserManageAdapter(UserManageActivity.this,R.layout.item_user_manage, null);
        userManageAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rv1.setAdapter(userManageAdapter);

        SmartRefreshLayout swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                String input = et_input.getText().toString().trim();
                LoadData(input);
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                 page  =1;
                String input = et_input.getText().toString().trim();
                SetData(input);
                refreshLayout.finishRefresh();
            }
        });
    }

    private void InitData(String query_name) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(UserManageActivity.this));
        map.put("user_level_id", user_level_id);
        map.put("query_name", query_name);
        map.put("recommand_level", recommand_level);
        map.put("page", page);
        map.put("limit", 4);


        OkGo.<String>post(Constants.CUSTOM_MANAGE)
                .params("user_id", SPUtils.getAppUserId(UserManageActivity.this))
                .params("user_level_id", user_level_id)
                .params("query_name", query_name)
                .params("recommand_level", recommand_level)
                .params("page", page)
                .params("limit", 4)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        UserManageBean luckRecordBean = gson.fromJson(response.body(), UserManageBean.class);

                        if (luckRecordBean.getCode() >= 0) {

                            Glide.with(mContext).load(luckRecordBean.getResult().getRecommand_user_head_img())
                                    .into(iv_recommand_user_head_img);
                            tv_recommand_user_real_name.setText(luckRecordBean.getResult().getRecommand_user_real_name());
                            recommand_user_phone = luckRecordBean.getResult().getRecommand_user_phone();

                            user_level_list = luckRecordBean.getResult().getUser_level_list();

                            for (int i = 0; i < user_level_list.size(); i++) {
                                tabList.add(user_level_list.get(i).getLevel_name());

                            }

                            for (int i = 0; i < tabList.size(); i++) {
                                mFragments.add(new SimpleCardFragment());
                            }

                            MyPagerAdapter mAdapter = new MyPagerAdapter(getSupportFragmentManager());
                            vp.setAdapter(mAdapter);
                            tl_5.setViewPager(vp);
                            tl_5.getTitleView(0).setTextSize(16f);
                            tl_5.getTitleView(0).invalidate();

                            bt_1.setText("全部  " + luckRecordBean.getResult().getTotal_custom_num());
                            bt_2.setText("直接  "+ luckRecordBean.getResult().getDirect_custom_num());
                            bt_3.setText("团队  "+ luckRecordBean.getResult().getTeam_custom_num());

                            userManageAdapter.setNewData(luckRecordBean.getResult().getUser_list());
                            View notDataView = getLayoutInflater().inflate(R.layout.item_empty_view, (ViewGroup) rv1.getParent(), false);
                            userManageAdapter.setEmptyView(notDataView);
                        } else {
                            Toast.makeText(UserManageActivity.this, luckRecordBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }







    private void SetData(String query_name) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(UserManageActivity.this));
        map.put("user_level_id", user_level_id);
        map.put("query_name", query_name);
        map.put("recommand_level", recommand_level);
        map.put("page", page);
        map.put("limit", 4);


        OkGo.<String>post(Constants.CUSTOM_MANAGE)
                .params("user_id", SPUtils.getAppUserId(UserManageActivity.this))
                .params("user_level_id", user_level_id)
                .params("query_name", query_name)
                .params("recommand_level", recommand_level)
                .params("page", page)
                .params("limit", 4)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        UserManageBean luckRecordBean = gson.fromJson(response.body(), UserManageBean.class);

                        if (luckRecordBean.getCode() >= 0) {

                            bt_1.setText("全部" + luckRecordBean.getResult().getTotal_custom_num());
                            bt_2.setText("直接"+ luckRecordBean.getResult().getDirect_custom_num());
                            bt_3.setText("团队"+ luckRecordBean.getResult().getTeam_custom_num());

                            userManageAdapter.setNewData(luckRecordBean.getResult().getUser_list());
                        } else {
                            Toast.makeText(UserManageActivity.this, luckRecordBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }



    private void LoadData(String query_name) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(UserManageActivity.this));
        map.put("user_level_id", user_level_id);
        map.put("query_name", query_name);
        map.put("recommand_level", recommand_level);
        map.put("page", page);
        map.put("limit", 4);


        OkGo.<String>post(Constants.CUSTOM_MANAGE)
                .params("user_id", SPUtils.getAppUserId(UserManageActivity.this))
                .params("user_level_id", user_level_id)
                .params("query_name", query_name)
                .params("recommand_level", recommand_level)
                .params("page", page)
                .params("limit", 4)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        UserManageBean luckRecordBean = gson.fromJson(response.body(), UserManageBean.class);

                        if (luckRecordBean.getCode() >= 0) {

                            bt_1.setText("全部" + luckRecordBean.getResult().getTotal_custom_num());
                            bt_2.setText("直接"+ luckRecordBean.getResult().getDirect_custom_num());
                            bt_3.setText("团队"+ luckRecordBean.getResult().getTeam_custom_num());

                            userManageAdapter.addData(luckRecordBean.getResult().getUser_list());
                        } else {
                            Toast.makeText(UserManageActivity.this, luckRecordBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabList.get(position);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }

    @Override
    public void onClick(View v) {
        String input = et_input.getText().toString().trim();
        switch (v.getId()) {

            case R.id.iv_close:
                finish();
                break;

            case R.id.ll_phone:
                //电话
                if (!TextUtils.isEmpty(recommand_user_phone)){
                    CallDialog callDialog = new CallDialog(UserManageActivity.this, new int[]{}, recommand_user_phone);
                    callDialog.show();
                    callDialog.setOnClickListener(new CallDialog.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            Intent Intent = new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel:" + recommand_user_phone));//跳转到拨号界面，同时传递电话号码
                            startActivity(Intent);
                        }

                    });

                }
                break;

            case R.id.rl_search:

                if (TextUtils.isEmpty(input)){
                    ToastUtils.showShort("请输入用户姓名或手机号");
                }else{
                    SetData(input);
                }
                break;

            case R.id.bt_1:
                page  =1;
                init_bt(1);
                recommand_level = 0;
                SetData(input);
                break;

            case R.id.bt_2:
                page  =1;
                init_bt(2);
                recommand_level = 1;
                SetData(input);
                break;
            case R.id.bt_3:
                page  =1;
                init_bt(3);
                recommand_level = 2;
                SetData(input);
                break;

            default:
                break;
        }
    }

    private void init_bt(int position) {
        switch (position) {
            case 1:
                bt_1.setTextColor(ContextCompat.getColor(UserManageActivity.this, R.color.white));
                bt_1.setBackground(ContextCompat.getDrawable(UserManageActivity.this, R.drawable.shanpe_green_12dp));
                bt_2.setTextColor(ContextCompat.getColor(UserManageActivity.this, R.color.green_bg2));
                bt_2.setBackground(ContextCompat.getDrawable(UserManageActivity.this, R.drawable.shanpe_gray_green_12dp));
                bt_3.setTextColor(ContextCompat.getColor(UserManageActivity.this, R.color.green_bg2));
                bt_3.setBackground(ContextCompat.getDrawable(UserManageActivity.this, R.drawable.shanpe_gray_green_12dp));
                break;

            case 2:
                bt_1.setTextColor(ContextCompat.getColor(UserManageActivity.this, R.color.green_bg2));
                bt_1.setBackground(ContextCompat.getDrawable(UserManageActivity.this, R.drawable.shanpe_gray_green_12dp));
                bt_2.setTextColor(ContextCompat.getColor(UserManageActivity.this, R.color.white));
                bt_2.setBackground(ContextCompat.getDrawable(UserManageActivity.this, R.drawable.shanpe_green_12dp));
                bt_3.setTextColor(ContextCompat.getColor(UserManageActivity.this, R.color.green_bg2));
                bt_3.setBackground(ContextCompat.getDrawable(UserManageActivity.this, R.drawable.shanpe_gray_green_12dp));
                break;

            case 3:
                bt_1.setTextColor(ContextCompat.getColor(UserManageActivity.this, R.color.green_bg2));
                bt_1.setBackground(ContextCompat.getDrawable(UserManageActivity.this, R.drawable.shanpe_gray_green_12dp));
                bt_2.setTextColor(ContextCompat.getColor(UserManageActivity.this, R.color.green_bg2));
                bt_2.setBackground(ContextCompat.getDrawable(UserManageActivity.this, R.drawable.shanpe_gray_green_12dp));
                bt_3.setTextColor(ContextCompat.getColor(UserManageActivity.this, R.color.white));
                bt_3.setBackground(ContextCompat.getDrawable(UserManageActivity.this, R.drawable.shanpe_green_12dp));
                break;
            default:
                break;
        }

    }
}
